import { Response } from 'express';
import { AuthenticatedRequest } from '../types/auth';
import { AIAssessmentService } from '../services/aiAssessmentService';
import { ApiError } from '../utils/ApiError';
import { StatusCodes } from '../constants/statusCodes';
import { logger } from '../utils/logger';
import { Role } from '@prisma/client';
import { z } from 'zod';

const batchAssessmentSchema = z.object({
  submissionIds: z.array(z.string().uuid('无效的提交ID')).min(1, '至少需要一个提交ID')
});

const reassessmentSchema = z.object({
  teacherFeedback: z.string().optional()
});

export const aiAssessmentController = {
  // 单个提交的AI评估
  async assessSubmission(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      const { submissionId } = req.params;

      // 验证教师权限
      if (req.user.role !== Role.ADMIN && req.user.role !== Role.TEACHER) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权进行AI评估');
      }

      const result = await AIAssessmentService.assessSubmission(submissionId);

      logger.info('AI评估完成', { submissionId, teacherId: req.user.id });
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      logger.error('AI评估失败', {
        context: 'aiAssessmentController.assessSubmission',
        error
      });
      throw error;
    }
  },

  // 批量提交的AI评估
  async batchAssessSubmissions(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      // 验证教师权限
      if (req.user.role !== Role.ADMIN && req.user.role !== Role.TEACHER) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权进行AI评估');
      }

      const { submissionIds } = batchAssessmentSchema.parse(req.body);

      const results = await AIAssessmentService.batchAssess(submissionIds);

      logger.info('批量AI评估完成', {
        teacherId: req.user.id,
        submissionCount: submissionIds.length
      });

      res.json({
        success: true,
        data: results
      });
    } catch (error) {
      logger.error('批量AI评估失败', {
        context: 'aiAssessmentController.batchAssessSubmissions',
        error
      });
      throw error;
    }
  },

  // 重新评估提交
  async reassessSubmission(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      // 验证教师权限
      if (req.user.role !== Role.ADMIN && req.user.role !== Role.TEACHER) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权进行AI评估');
      }

      const { submissionId } = req.params;
      const { teacherFeedback } = reassessmentSchema.parse(req.body);

      const result = await AIAssessmentService.reassessSubmission(
        submissionId,
        teacherFeedback
      );

      logger.info('重新评估完成', {
        submissionId,
        teacherId: req.user.id,
        hasTeacherFeedback: !!teacherFeedback
      });

      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      logger.error('重新评估失败', {
        context: 'aiAssessmentController.reassessSubmission',
        error
      });
      throw error;
    }
  },

  // 获取评估历史
  async getAssessmentHistory(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      const { submissionId } = req.params;

      // 验证教师权限
      if (req.user.role !== Role.ADMIN && req.user.role !== Role.TEACHER) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权查看评估历史');
      }

      const history = await prisma.assessmentHistory.findMany({
        where: { submissionId },
        orderBy: { createdAt: 'desc' }
      });

      res.json({
        success: true,
        data: history
      });
    } catch (error) {
      logger.error('获取评估历史失败', {
        context: 'aiAssessmentController.getAssessmentHistory',
        error
      });
      throw error;
    }
  }
};
